package aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/4/12.
 */
public class TimeServerHandle implements Runnable{

    CountDownLatch latch;

    AsynchronousServerSocketChannel serverSocketChannel;

    public TimeServerHandle(int port) {
        try{
            serverSocketChannel = AsynchronousServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port : "+port);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try{
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept(){
        serverSocketChannel.accept(this,new AcceptCompletionHandler());
        System.out.println("first accept client");
    }
}
